package com.gs.zxinglibrary.zxing.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.gs.zxinglibrary.R;


/**
 * Initial the camera
 * <p>
 * 默认的二维码扫描Activity
 */
public class CaptureActivity extends AppCompatActivity {
    public static final String TYPE = "type"; // 1不带按钮 0带按钮
    public static final String MY_ACTION = "com.gaoyi.crm.mybroadcast";
    private int mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture);

        mType = getIntent().getIntExtra(TYPE, 0);
        CaptureFragment captureFragment = new CaptureFragment();
        captureFragment.setType(mType);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
        captureFragment.setCameraInitCallBack(new CaptureFragment.CameraInitCallBack() {
            @Override
            public void callBack(Exception e) {
                if (e == null) {

                } else {
                    Log.e("TAG", "callBack: ", e);
                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        resultFinish(CodeUtils.RESULT_BACK,"");
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            resultFinish(CodeUtils.RESULT_SUCCESS,result);
        }

        @Override
        public void onAnalyzeFailed() {
            resultFinish(CodeUtils.RESULT_FAILED,"");
        }

        @Override
        public void onBack() {
            resultFinish(CodeUtils.RESULT_BACK,"");
        }

        @Override
        public void onFinish() {
            resultFinish(CodeUtils.RESULT_FINISH,"");
        }
    };

    private void resultFinish(int resultType,String result) {
        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(CodeUtils.RESULT_TYPE, resultType);
        bundle.putString(CodeUtils.RESULT_STRING, result);
        resultIntent.putExtras(bundle);
        CaptureActivity.this.setResult(RESULT_OK, resultIntent);
        CaptureActivity.this.finish();
    }
}